package sports;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import bean.User_record;
import algorithm.Point_record;
import algorithm.Running_credit;
import DB.DB_connection_pool;

public class Running_handle extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		JSONObject jsonObj = new JSONObject();
		String user_account = request.getSession().getAttribute("user_account").toString();
		
		int running_time = Integer.parseInt(request.getParameter("running_time"));   //跑步时间(秒)
		int running_level = Integer.parseInt(request.getParameter("running_level"));    //1~4
		int running_type = Integer.parseInt(request.getParameter("running_type"));		//跑步类型，0短跑，1长跑
		double running_record = User_record.getRunning_record(user_account);    //历史记录
		
		try {
		Connection conn = DB_connection_pool.data_pool.getConnection();
		
		Running_credit running_credit = new Running_credit();
		Map<String,Double> map = running_credit.Get_running_score(running_time, running_level, running_type, running_record);
		
		Point_record point_record = new Point_record();
		point_record.sports_record(user_account, map.get("running_record"), Point_record.running_event);   //改变游泳历史记录
		if(map.get("flag") == 1){ //积分改变
			point_record.point_record(user_account, Point_record.running_event, map.get("running_credit"), true);   //记录
			point_record.change_point(user_account, map.get("running_credit"));
		}else{    
			//do not
		}
		
		
		//插入数据
		String insert_sql = "insert into running_parameter(user_account , running_time , running_level , running_type) values(?,?,?,?)";
		PreparedStatement ps_insert = conn.prepareStatement(insert_sql);
		ps_insert.setString(1, user_account);
		ps_insert.setInt(2, running_time);
		ps_insert.setInt(3, running_level);
		ps_insert.setInt(4, running_type);
		ps_insert.executeUpdate();
		ps_insert.close();
				
		conn.close();
		jsonObj.put("result", true);
	
		} catch (SQLException e) {
			jsonObj.put("result", false);
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		out.print(jsonObj.toString());
		
	}

}
